package com.project;

import com.project.config.WebMvcConfig;
import com.project.filter.*;
import org.apache.catalina.Context;
import org.apache.catalina.LifecycleException;
import org.apache.catalina.Wrapper;
import org.apache.catalina.startup.Tomcat;
import org.apache.tomcat.util.descriptor.web.FilterDef;
import org.apache.tomcat.util.descriptor.web.FilterMap;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.servlet.DispatcherServlet;

import javax.servlet.Filter;
import javax.servlet.ServletContext;

/**
 * @Author(王思翰)
 * @Description(类的描述)TomcatMain类
 * @Date(创建时间)
 */
public class Main {
    public Main() {
        //创建Tomcat
        Tomcat tomcat = new Tomcat();
        //设置端口号,端口号需自己输入
        tomcat.setPort(8088);
        //引导http引擎
        tomcat.getConnector();

        //创建上下文对象
        Context context = tomcat.addContext("", null);
        this.registerFilter(context,new CharFilter(),"/*");
        this.registerFilter(context,new CustomFilter(),"/html/custom/*");
        this.registerFilter(context,new ManagerFilter(),"/html/manager/*");
        this.registerFilter(context,new SendFilter(),"/html/send/*");
        this.registerFilter(context,new AssFilter(),"/html/ass/*");

        WebApplicationContext wac = createApplicationContext(context.getServletContext());

        //创建前端控制器对象
        DispatcherServlet dis = new DispatcherServlet(wac);
        //注册前端控制器
        Wrapper wrp = tomcat.addServlet(context, "dis", dis);

        //初始化容器
        wrp.setLoadOnStartup(0);
        //以什么路径访问
        wrp.addMapping("/*");

        try {
            //启动Tomcat
            tomcat.start();
        } catch (LifecycleException e) {
            e.printStackTrace();
        }
    }

    /**
     * 创建springMAV应用上下文
     *
     * @param servletContext
     * @return
     */
    public static WebApplicationContext createApplicationContext(
            ServletContext servletContext) {
        AnnotationConfigWebApplicationContext ctx
                = new AnnotationConfigWebApplicationContext();
        ctx.register(WebMvcConfig.class);

        ctx.setServletContext(servletContext);
        ctx.refresh();
        ctx.registerShutdownHook();
        return ctx;
    }

    /**
     * 注册过滤器
     * @param filterObj 过滤器对象
     * @param urlPattern 过滤范围
     */
    public void registerFilter(Context context,Filter filterObj,String urlPattern){
        FilterDef fd=new FilterDef();
        fd.setFilterName(filterObj.getClass().getName());
        fd.setFilter(filterObj);

        FilterMap fm=new FilterMap();
        fm.setFilterName(filterObj.getClass().getName());
        fm.addURLPattern(urlPattern);

        context.addFilterDef(fd);
        context.addFilterMap(fm);
    }

    public static void main(String[] args) {
        new Main();
    }
}
